$(function() {
    function validate(_formData) {
        var validate = true;
        $.each(_formData, function(i, field) {
            if(validate && field.name == 'user.name' && field.value == '') {
                layer.msg('账户不能为空！！', {icon: 2});
                validate = false;
            }
            if(validate && field.name == 'user.password' && field.value == '') {
                layer.msg('密码不能为空！！', {icon: 2});
                validate = false;
            }
        });
        return validate;
    }
    $('#login-btn').click(function() {
        var formData = $('#auth-login-form').serializeArray();
        if(validate(formData)) {
            var formServerData = new Object();
            $.each(formData, function(i, field) {
                if(field.name == 'user.name') {
                    formServerData.username = field.value;
                }
                if(field.name == 'user.password') {
                    formServerData.password = field.value;
                }
            });
            //console.log(JSON.stringify(formServerData));
            $.ajax({
                url: '/auth/doLogin',
                data: JSON.stringify(formServerData),
                dataType: 'json',
                method: 'post',
                headers : {'Content-type':'application/json;charset=utf-8'},
                before: function() {
                    $('#login-btn').val('登录中...');
                },
                success: function(_response) {
                    if(_response.isSuccess) {
                        layer.msg('登录成功，系统跳转中...', {icon: 1});
                        window.location.href = '/home';
                    } else {
                        layer.msg(_response.message, {icon: 2});
                    }
                },
                error: function(xhr, textStatus) {
                    console.log(xhr);
                }
            });
        }
    });
});